package cn.com.smart.framework.manager;

import java.util.TimerTask;
import java.util.concurrent.Callable;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import cn.com.smart.common.utils.Threads;
import cn.com.smart.common.utils.spring.SpringUtils;

/**
 * 异步任务管理器
 * 
 */
public class TaskManager
{
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 任务调度线程池
     */
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    /**
     * 单例模式
     */
    private static enum Singleton{
    	INSTANCE;
    	private TaskManager tpm;
    	private Singleton() {
    		tpm = new TaskManager();
    	}
    	
    	public TaskManager getInstance() {
    		return tpm;
    	}
    }
    
    public static TaskManager me() {
    	return Singleton.INSTANCE.getInstance();
    }

    /**
     * 执行任务
     * 
     * @param task 任务
     */
    public void execute(TimerTask task)
    {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }
    
    public void execute(Runnable task) {
    	executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }
    
    public <V> ScheduledFuture<V> execute(Callable<V> task) {
    	return executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown()
    {
        Threads.shutdownAndAwaitTermination(executor);
    }
}
